package com.colmmcsky.twit2lj;

import java.util.Calendar;

import com.colmmcsky.twit2lj.R;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;

public class MainActivity extends Activity {
	private TextView mLog;
	private TextView mTimeDisplay;
	
	private CheckBox mPostAutomaticallyCheckBox;
	private CheckBox mPostPrivatelyCheckBox;
	private CheckBox mPostHidefCheckBox;
	
	private CheckBox mPostMonthlyAutomaticallyCheckBox;
	private CheckBox mPostMonthlyPrivatelyCheckBox;
	private CheckBox mPostMonthlyHidefCheckBox;
	
	private CheckBox mPrefixMyUsernameCheckBox;
	private CheckBox mPostRTsCheckBox;
	private CheckBox mPostRepliesCheckBox;
	
	private TextView mTwitterAccount;
	private TextView mLivejournalAccount;

	public static final String PrefsName = "Twit2LjPrefs";
	public static final String LogKey = "log";
	public static final String HourKey = "hour";
	public static final String MinuteKey = "minute";
	
	public static final String AutoPostKey = "autoPost";
	public static final String PrivatePostKey = "privatePost";
	public static final String HidefPostKey = "highdefPost";
	
	public static final String AutoMonthlyPostKey = "autoMonthlyPost";
	public static final String PrivateMonthlyPostKey = "privateMonthlyPost";
	public static final String HidefMonthlyPostKey = "highdefMonthlyPost";
	
	public static final String PrefixMyUsernameKey = "prefixMyUsername";
	public static final String PostRTsKey = "postRTs";
	public static final String PostRepliesKey = "postReplies";
	
	public static final String TwitterAccountKey = "twitterAccount";
	public static final String LivejournalAccountKey = "livejournalAccount";
	public static final String LivejournalPasswordKey = "livejournalPassword";
	
	private LogUpdater mLogUpdater;

    private int mHour;
    private int mMinute;

    static final int TIME_DIALOG_ID = 0;
    static final int ACCOUNTS_DIALOG_ID = 1;
    
	public class PostDayButtonClickListener implements OnClickListener {
    	MainActivity mActivity;
		
		PostDayButtonClickListener(MainActivity activity) {
    		mActivity = activity;
		}

		public void onClick(View v) {
			mActivity.PostDay();
		}
	}

	public class PostMonthButtonClickListener implements OnClickListener {
    	MainActivity mActivity;
		
		PostMonthButtonClickListener(MainActivity activity) {
    		mActivity = activity;
		}

		public void onClick(View v) {
			mActivity.PostMonth();
		}
	}

    private class SaveConfigClickListener  implements OnClickListener {
    	MainActivity mActivity;
    	
    	SaveConfigClickListener(MainActivity activity) {
    		mActivity = activity;
    	}
    	
		public void onClick(View v) {
			mActivity.SaveConfig();
		}
    }

    private class RefreshLogButtonClickListener  implements OnClickListener {
    	MainActivity mActivity;
    	
    	RefreshLogButtonClickListener(MainActivity activity) {
    		mActivity = activity;
    	}
    	
		public void onClick(View v) {
			mActivity.RefreshLog();
		}
    }

    private class ClearLogButtonClickListener  implements OnClickListener {
    	MainActivity mActivity;
    	
    	ClearLogButtonClickListener(MainActivity activity) {
    		mActivity = activity;
    	}
    	
		public void onClick(View v) {
			mActivity.ClearLog();
		}
    }

    public void SaveConfig() {
    	SaveFields();
    	LoadFields();
    	UpdateLog(mLogUpdater, "Config Saved.");
    	SetAlarm(MainActivity.this, mLogUpdater, false);
    }
    
    public void PostDay() {
    	SaveConfig();
    	PostWorker worker = new PostWorker(	mLogUpdater, getApplicationContext(), true, false);    	
		worker.start();  
    }

    public void PostMonth() {
    	SaveConfig();
    	PostWorker worker = new PostWorker(	mLogUpdater, getApplicationContext(), false, true);    	
		worker.start();  
    }

    public void RefreshLog() {
    	SharedPreferences preferences = getSharedPreferences(MainActivity.PrefsName, 0);
    	mLog.setText(preferences.getString(LogKey, ""));
    }

    public void ClearLog() {
    	SharedPreferences preferences = getSharedPreferences(MainActivity.PrefsName, 0);

		SharedPreferences.Editor editor = preferences.edit();
		
		editor.putString(MainActivity.LogKey, "");
		editor.commit();
 	
    	mLog.setText(preferences.getString(LogKey, ""));
    }

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);        

        setContentView(R.layout.main);
        
        mLog = (TextView)findViewById(R.id.textview);
        Button setupAccountsButton = (Button)findViewById(R.id.setupAccounts);
        Button setTimeButton = (Button)findViewById(R.id.setTimeButton);
        Button postDayButton = (Button)findViewById(R.id.postDayButton);
        Button postMonthButton = (Button)findViewById(R.id.postMonthButton);
        Button refreshLogButton = (Button)findViewById(R.id.refreshLogButton);
        Button clearLogButton = (Button)findViewById(R.id.clearLogButton);
        mTimeDisplay = (TextView)findViewById(R.id.timeText);
        
        mPostAutomaticallyCheckBox = (CheckBox)findViewById(R.id.automaticPosting);
        mPostPrivatelyCheckBox = (CheckBox)findViewById(R.id.privatePosting);
        mPostHidefCheckBox = (CheckBox)findViewById(R.id.hidefPosting);

        mPostMonthlyAutomaticallyCheckBox = (CheckBox)findViewById(R.id.automaticMonthlyPosting);
        mPostMonthlyPrivatelyCheckBox = (CheckBox)findViewById(R.id.privateMonthlyPosting);
        mPostMonthlyHidefCheckBox = (CheckBox)findViewById(R.id.hidefMonthlyPosting);

        mPrefixMyUsernameCheckBox = (CheckBox)findViewById(R.id.prefixWithMyUsername);
        mPostRTsCheckBox = (CheckBox)findViewById(R.id.postRTs);
        mPostRepliesCheckBox = (CheckBox)findViewById(R.id.postReplies);
        
        mTwitterAccount = (TextView)findViewById(R.id.twitterAccount);
        mLivejournalAccount = (TextView)findViewById(R.id.livejournalAccount);

        mLogUpdater = new LogUpdater(getSharedPreferences(MainActivity.PrefsName, 0), mLog);    	

        setTimeButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(TIME_DIALOG_ID);
            }
        });

        setupAccountsButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(ACCOUNTS_DIALOG_ID);
            }
        });

    	postDayButton.setOnClickListener(new PostDayButtonClickListener(this));
    	postMonthButton.setOnClickListener(new PostMonthButtonClickListener(this));
    	refreshLogButton.setOnClickListener(new RefreshLogButtonClickListener(this));
    	clearLogButton.setOnClickListener(new ClearLogButtonClickListener(this));
    	
    	mPostAutomaticallyCheckBox.setOnClickListener(new SaveConfigClickListener(this));
    	mPostPrivatelyCheckBox.setOnClickListener(new SaveConfigClickListener(this));
    	mPostHidefCheckBox.setOnClickListener(new SaveConfigClickListener(this));

    	mPostMonthlyAutomaticallyCheckBox.setOnClickListener(new SaveConfigClickListener(this));
    	mPostMonthlyPrivatelyCheckBox.setOnClickListener(new SaveConfigClickListener(this));
    	mPostMonthlyHidefCheckBox.setOnClickListener(new SaveConfigClickListener(this));

    	mPrefixMyUsernameCheckBox.setOnClickListener(new SaveConfigClickListener(this));
    	mPostRTsCheckBox.setOnClickListener(new SaveConfigClickListener(this));
    	mPostRepliesCheckBox.setOnClickListener(new SaveConfigClickListener(this));
    	
    	LoadFields();
    }
    
 // updates the time we display in the TextView
    private void updateTimeDisplay() {
        mTimeDisplay.setText(timeString(mHour, mMinute));
    }

    private static String timeString(int hour, int minute)
    {
    	boolean am = hour < 12;
    	int normHour = am ? hour : hour-12;
    	normHour = normHour == 0 ? 12 : normHour;
    	
    	StringBuilder builder = new StringBuilder();
    	builder.append(normHour);
    	builder.append(":");
    	builder.append(pad(minute));
    	builder.append(am ? " AM" : " PM");
    	
    	return builder.toString();
    }
    
    private static String pad(int c) {
        if (c >= 10)
            return String.valueOf(c);
        else
            return "0" + String.valueOf(c);
    }
    
 // the callback received when the user "sets" the time in the dialog
    private TimePickerDialog.OnTimeSetListener mTimeSetListener =
        new TimePickerDialog.OnTimeSetListener() {
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                mHour = hourOfDay;
                mMinute = minute;
                SaveConfig();
                updateTimeDisplay();
            }
        };
        
        @Override
        protected Dialog onCreateDialog(int id) {
            switch (id) {
            case TIME_DIALOG_ID:
                return new TimePickerDialog(this,
                        mTimeSetListener, mHour, mMinute, false);
                
            case ACCOUNTS_DIALOG_ID:
            	LayoutInflater factory = LayoutInflater.from(this);
                final View textEntryView = factory.inflate(R.layout.accounts, null);
                  	
                // fill in the text boxes with saved info
            	EditText twitterAccount = (EditText)textEntryView.findViewById(R.id.twitterAccount);
            	EditText livejournalAccount = (EditText)textEntryView.findViewById(R.id.livejournalAccount);
            	EditText livejournalPassword = (EditText)textEntryView.findViewById(R.id.livejournalPassword); 
            	
            	SharedPreferences preferences = getSharedPreferences(MainActivity.PrefsName, 0);
            	twitterAccount.setText(preferences.getString(TwitterAccountKey, ""));
            	livejournalAccount.setText(preferences.getString(LivejournalAccountKey, ""));
            	livejournalPassword.setText(preferences.getString(LivejournalPasswordKey, ""));
           	         
                return new AlertDialog.Builder(this)
                    .setTitle("Enter Account Info")
                    .setView(textEntryView)
                    .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            /* User clicked OK so save the account info */
                        	EditText twitterAccount = (EditText)textEntryView.findViewById(R.id.twitterAccount);
                        	EditText livejournalAccount = (EditText)textEntryView.findViewById(R.id.livejournalAccount);
                        	EditText livejournalPassword = (EditText)textEntryView.findViewById(R.id.livejournalPassword); 
                        	
                        	SharedPreferences.Editor preferences = getSharedPreferences(MainActivity.PrefsName, 0).edit();                        	
                        	preferences.putString(TwitterAccountKey, twitterAccount.getText().toString());
                        	preferences.putString(LivejournalAccountKey, livejournalAccount.getText().toString());
                        	preferences.putString(LivejournalPasswordKey, livejournalPassword.getText().toString());
                        	preferences.commit();

                        	SaveConfig();
                        }
                    })
                    .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            /* User clicked cancel so do nothing */
                        }
                    })
                    .create();
            }
            return null;
        }
    
    // Load preferences
    private void LoadFields() {
    	SharedPreferences preferences = getSharedPreferences(MainActivity.PrefsName, 0);
    	
    	mHour = preferences.getInt(HourKey, 4);
    	mMinute = preferences.getInt(MinuteKey, 0);
    	
    	mPostAutomaticallyCheckBox.setChecked(preferences.getBoolean(AutoPostKey, true));
    	mPostPrivatelyCheckBox.setChecked(preferences.getBoolean(PrivatePostKey, false));
    	mPostHidefCheckBox.setChecked(preferences.getBoolean(HidefPostKey, false));

    	mPostMonthlyAutomaticallyCheckBox.setChecked(preferences.getBoolean(AutoMonthlyPostKey, true));
    	mPostMonthlyPrivatelyCheckBox.setChecked(preferences.getBoolean(PrivateMonthlyPostKey, true));
    	mPostMonthlyHidefCheckBox.setChecked(preferences.getBoolean(HidefMonthlyPostKey, true));

    	mPrefixMyUsernameCheckBox.setChecked(preferences.getBoolean(PrefixMyUsernameKey, false));
    	mPostRTsCheckBox.setChecked(preferences.getBoolean(PostRTsKey, true));
    	mPostRepliesCheckBox.setChecked(preferences.getBoolean(PostRepliesKey, true));
    	
    	mTwitterAccount.setText(preferences.getString(TwitterAccountKey, ""));
    	mLivejournalAccount.setText(preferences.getString(LivejournalAccountKey, ""));
    	
    	mLog.setText(preferences.getString(LogKey, ""));

        updateTimeDisplay();
    }
    
    // Save preferences
    private void SaveFields() {
    	SharedPreferences.Editor preferences = getSharedPreferences(MainActivity.PrefsName, 0).edit();
    	
    	preferences.putInt(HourKey, mHour);
    	preferences.putInt(MinuteKey, mMinute);
    	
    	preferences.putBoolean(AutoPostKey, mPostAutomaticallyCheckBox.isChecked());
    	preferences.putBoolean(PrivatePostKey, mPostPrivatelyCheckBox.isChecked());
    	preferences.putBoolean(HidefPostKey, mPostHidefCheckBox.isChecked());

    	preferences.putBoolean(AutoMonthlyPostKey, mPostMonthlyAutomaticallyCheckBox.isChecked());
    	preferences.putBoolean(PrivateMonthlyPostKey, mPostMonthlyPrivatelyCheckBox.isChecked());
    	preferences.putBoolean(HidefMonthlyPostKey, mPostMonthlyHidefCheckBox.isChecked());

    	preferences.putBoolean(PrefixMyUsernameKey, mPrefixMyUsernameCheckBox.isChecked());
    	preferences.putBoolean(PostRTsKey, mPostRTsCheckBox.isChecked());
    	preferences.putBoolean(PostRepliesKey, mPostRepliesCheckBox.isChecked());

    	preferences.commit();
    }
    
    public static void UpdateLog(LogUpdater logUpdater, String str)
    {
        if (logUpdater != null)
        {
	        Message message = Message.obtain();			
	        message.obj = str;  
        	logUpdater.sendMessage(message);
        }
    }
    
    public static void SetAlarm(Context context, LogUpdater logUpdater, boolean retry) {
    	SharedPreferences preferences = context.getSharedPreferences(MainActivity.PrefsName, 0);

        Calendar alarm = Calendar.getInstance();  
    	if (retry) {
    		// set for 20 minutes from now
        	alarm.add(Calendar.MINUTE, 20);  
    	} else {    		    	
    		// set for the next day's normal time
	    	int hour = preferences.getInt(HourKey, 4);
	    	int minute = preferences.getInt(MinuteKey, 4);
	    	      
	        alarm.set(Calendar.HOUR_OF_DAY, hour);
	        alarm.set(Calendar.MINUTE, minute);
	        alarm.set(Calendar.SECOND, 0);
	        alarm.set(Calendar.MILLISECOND, 0);
	        
	        // if the alarm time has already passed today, set it to tomorrow
	        Calendar now = Calendar.getInstance();
	        if (now.compareTo(alarm) == 1){
	        	alarm.add(Calendar.DAY_OF_MONTH, 1);        	
	        }
    	}
        // When the alarm goes off, we want to broadcast an Intent to our
        // BroadcastReceiver.  Here we make an Intent with an explicit class
        // name to have our own receiver (which has been published in
        // AndroidManifest.xml) instantiated and called, and then create an
        // IntentSender to have the intent executed as a broadcast.
        // Note that unlike above, this IntentSender is configured to
        // allow itself to be sent multiple times.
        Intent intent = new Intent(context, AutorunBroadcastReceiver.class);
        PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);

        // Schedule the alarm!
        AlarmManager am = (AlarmManager)context.getSystemService(ALARM_SERVICE);
        am.setRepeating(AlarmManager.RTC_WAKEUP,
        				alarm.getTimeInMillis(), 
		        		AlarmManager.INTERVAL_DAY, 
		        		sender);
        
        // note the new alarm in the log
        UpdateLog(logUpdater,
        		"Alarm Set: " + 
	        	(1+alarm.get(Calendar.MONTH)) + "/" +
	        	alarm.get(Calendar.DAY_OF_MONTH) + "-" +
	        	pad(alarm.get(Calendar.HOUR_OF_DAY)) + ":" +
	        	pad(alarm.get(Calendar.MINUTE)));
    }    
}